import { getOptimizedDeepSeekClient } from '@/lib/deepseek';
import { ChatMessage } from '@/types';
import { HumanMessage, SystemMessage } from '@langchain/core/messages';

/**
 * 用户意图类型
 */
export enum UserIntent {
  QUESTION = 'question', // 询问问题
  INSTRUCTION = 'instruction', // 指令请求
  CONVERSATION = 'conversation', // 日常对话
  CLARIFICATION = 'clarification', // 澄清说明
  COMPLAINT = 'complaint', // 投诉抱怨
  PRAISE = 'praise', // 表扬赞美
  HELP = 'help', // 寻求帮助
  INFORMATION = 'information', // 信息查询
  CREATIVE = 'creative', // 创意创作
  ANALYSIS = 'analysis', // 分析评估
  UNKNOWN = 'unknown', // 未知意图
}

/**
 * 意图识别结果
 */
interface IntentResult {
  intent: UserIntent;
  confidence: number;
  keywords: string[];
  context: string;
  urgency: 'low' | 'medium' | 'high';
  complexity: 'simple' | 'medium' | 'complex';
  emotionalTone: 'positive' | 'neutral' | 'negative';
  suggestedResponse: ResponseStrategy;
}

/**
 * 响应策略
 */
interface ResponseStrategy {
  tone: 'formal' | 'casual' | 'empathetic' | 'professional' | 'creative';
  length: 'brief' | 'moderate' | 'detailed';
  structure: 'direct' | 'explanatory' | 'step_by_step' | 'conversational';
  includeExamples: boolean;
  includeFollowUp: boolean;
  priority: 'accuracy' | 'helpfulness' | 'engagement' | 'efficiency';
}

/**
 * 用户画像
 */
interface UserProfile {
  preferredTone: string;
  complexityLevel: string;
  commonTopics: string[];
  responseLength: string;
  interactionStyle: string;
  lastInteractionTime?: Date;
  totalInteractions: number;
}

/**
 * 对话意图识别和个性化响应服务
 */
export class IntentRecognitionService {
  private userProfiles: Map<string, UserProfile> = new Map();
  private intentPatterns: Map<UserIntent, RegExp[]> = new Map();

  constructor() {
    this.initializeIntentPatterns();
  }

  /**
   * 初始化意图识别模式
   */
  private initializeIntentPatterns(): void {
    this.intentPatterns.set(UserIntent.QUESTION, [
      /^(什么|怎么|如何|为什么|哪里|谁|何时|多少)/,
      /(\?|？)$/,
      /请问|想知道|了解|咨询/,
    ]);

    this.intentPatterns.set(UserIntent.INSTRUCTION, [
      /^(请|帮我|帮忙|能否|可以)/,
      /(做|创建|生成|制作|写|画|设计)/,
      /需要你|要求|指令/,
    ]);

    this.intentPatterns.set(UserIntent.HELP, [
      /帮助|救命|不会|不懂|困难|问题/,
      /求助|指导|教|学/,
    ]);

    this.intentPatterns.set(UserIntent.COMPLAINT, [
      /不满|抱怨|投诉|差|糟糕|失望/,
      /问题|错误|bug|故障/,
    ]);

    this.intentPatterns.set(UserIntent.PRAISE, [
      /好|棒|优秀|完美|满意|感谢/,
      /赞|夸|表扬|喜欢/,
    ]);

    this.intentPatterns.set(UserIntent.CREATIVE, [
      /创作|创意|想象|故事|诗歌|小说/,
      /设计|艺术|音乐|绘画/,
    ]);

    this.intentPatterns.set(UserIntent.ANALYSIS, [
      /分析|评估|比较|总结|归纳/,
      /优缺点|利弊|评价|判断/,
    ]);
  }

  /**
   * 识别用户意图
   */
  async recognizeIntent(
    message: string,
    conversationHistory: ChatMessage[] = [],
    userId?: string
  ): Promise<IntentResult> {
    try {
      // 1. 基于规则的初步识别
      const ruleBasedIntent = this.ruleBasedIntentRecognition(message);

      // 2. 基于AI的深度分析
      const aiBasedIntent = await this.aiBasedIntentRecognition(
        message,
        conversationHistory
      );

      // 3. 融合结果
      const finalIntent = this.fuseIntentResults(
        ruleBasedIntent,
        aiBasedIntent
      );

      // 4. 分析上下文和情感
      const context = this.analyzeContext(message, conversationHistory);
      const emotionalTone = this.analyzeEmotionalTone(message);
      const urgency = this.analyzeUrgency(message);
      const complexity = this.analyzeComplexity(message);

      // 5. 生成个性化响应策略
      const responseStrategy = this.generateResponseStrategy(
        finalIntent,
        context,
        emotionalTone,
        userId
      );

      // 6. 提取关键词
      const keywords = this.extractKeywords(message);

      return {
        intent: finalIntent.intent,
        confidence: finalIntent.confidence,
        keywords,
        context,
        urgency,
        complexity,
        emotionalTone,
        suggestedResponse: responseStrategy,
      };
    } catch (error) {
      console.error('意图识别失败:', error);
      return this.createFallbackIntentResult(message);
    }
  }

  /**
   * 基于规则的意图识别
   */
  private ruleBasedIntentRecognition(message: string): {
    intent: UserIntent;
    confidence: number;
  } {
    const messageLower = message.toLowerCase();
    let bestMatch = { intent: UserIntent.UNKNOWN, confidence: 0 };

    for (const [intent, patterns] of this.intentPatterns.entries()) {
      let matchCount = 0;

      for (const pattern of patterns) {
        if (pattern.test(messageLower)) {
          matchCount++;
        }
      }

      const confidence = matchCount / patterns.length;
      if (confidence > bestMatch.confidence) {
        bestMatch = { intent, confidence };
      }
    }

    // 如果没有明确匹配，根据长度和结构推断
    if (bestMatch.confidence < 0.3) {
      if (message.includes('?') || message.includes('？')) {
        bestMatch = { intent: UserIntent.QUESTION, confidence: 0.6 };
      } else if (message.length > 100) {
        bestMatch = { intent: UserIntent.INSTRUCTION, confidence: 0.4 };
      } else {
        bestMatch = { intent: UserIntent.CONVERSATION, confidence: 0.3 };
      }
    }

    return bestMatch;
  }

  /**
   * 基于AI的意图识别
   */
  private async aiBasedIntentRecognition(
    message: string,
    history: ChatMessage[]
  ): Promise<{ intent: UserIntent; confidence: number }> {
    const contextText = history
      .slice(-3)
      .map(msg => `${msg.role}: ${msg.content}`)
      .join('\n');

    const prompt = `请分析以下用户消息的意图类型：

对话历史：
${contextText}

当前消息：${message}

请从以下选项中选择最合适的意图类型：
- question: 询问问题
- instruction: 指令请求
- conversation: 日常对话
- clarification: 澄清说明
- complaint: 投诉抱怨
- praise: 表扬赞美
- help: 寻求帮助
- information: 信息查询
- creative: 创意创作
- analysis: 分析评估
- unknown: 未知意图

请只返回意图类型和置信度（0-1），格式：intent:confidence`;

    try {
      const client = getOptimizedDeepSeekClient('analytical');
      const response = await client.invoke([
        new SystemMessage(
          '你是一个专业的意图识别助手，能够准确分析用户消息的意图。'
        ),
        new HumanMessage(prompt),
      ]);

      const result = response.content as string;
      const match = result.match(/(\w+):(\d*\.?\d+)/);

      if (match) {
        const intentStr = match[1];
        const confidence = parseFloat(match[2]);

        const intent = Object.values(UserIntent).includes(
          intentStr as UserIntent
        )
          ? (intentStr as UserIntent)
          : UserIntent.UNKNOWN;

        return { intent, confidence: Math.min(confidence, 1.0) };
      }
    } catch (error) {
      console.error('AI意图识别失败:', error);
    }

    return { intent: UserIntent.UNKNOWN, confidence: 0.1 };
  }

  /**
   * 融合意图识别结果
   */
  private fuseIntentResults(
    ruleResult: { intent: UserIntent; confidence: number },
    aiResult: { intent: UserIntent; confidence: number }
  ): { intent: UserIntent; confidence: number } {
    // 如果两个结果一致，提高置信度
    if (ruleResult.intent === aiResult.intent) {
      return {
        intent: ruleResult.intent,
        confidence: Math.min(
          (ruleResult.confidence + aiResult.confidence) / 2 + 0.2,
          1.0
        ),
      };
    }

    // 选择置信度更高的结果
    return ruleResult.confidence > aiResult.confidence ? ruleResult : aiResult;
  }

  /**
   * 分析上下文
   */
  private analyzeContext(message: string, history: ChatMessage[]): string {
    if (history.length === 0) return 'new_conversation';

    const recentMessages = history.slice(-3);
    const topics = recentMessages
      .map(msg => this.extractKeywords(msg.content))
      .flat()
      .slice(0, 5);

    if (topics.length > 0) {
      return `continuing_discussion_about_${topics.join('_')}`;
    }

    return 'ongoing_conversation';
  }

  /**
   * 分析情感倾向
   */
  private analyzeEmotionalTone(
    message: string
  ): 'positive' | 'neutral' | 'negative' {
    const positiveWords = [
      '好',
      '棒',
      '优秀',
      '感谢',
      '满意',
      '喜欢',
      '完美',
      '成功',
    ];
    const negativeWords = [
      '坏',
      '差',
      '糟糕',
      '失望',
      '不满',
      '错误',
      '问题',
      '困难',
    ];

    const messageLower = message.toLowerCase();

    let positiveScore = 0;
    let negativeScore = 0;

    for (const word of positiveWords) {
      if (messageLower.includes(word)) positiveScore++;
    }

    for (const word of negativeWords) {
      if (messageLower.includes(word)) negativeScore++;
    }

    if (positiveScore > negativeScore) return 'positive';
    if (negativeScore > positiveScore) return 'negative';
    return 'neutral';
  }

  /**
   * 分析紧急程度
   */
  private analyzeUrgency(message: string): 'low' | 'medium' | 'high' {
    const urgentWords = ['紧急', '急', '马上', '立即', '快', '赶紧', '救命'];
    const messageLower = message.toLowerCase();

    for (const word of urgentWords) {
      if (messageLower.includes(word)) return 'high';
    }

    if (message.includes('!') || message.includes('！')) return 'medium';

    return 'low';
  }

  /**
   * 分析复杂程度
   */
  private analyzeComplexity(message: string): 'simple' | 'medium' | 'complex' {
    const wordCount = message.split(/\s+/).length;
    const hasMultipleQuestions = (message.match(/[?？]/g) || []).length > 1;
    const hasComplexStructure =
      message.includes('如果') ||
      message.includes('但是') ||
      message.includes('然而');

    if (wordCount > 50 || hasMultipleQuestions || hasComplexStructure) {
      return 'complex';
    }

    if (wordCount > 20) {
      return 'medium';
    }

    return 'simple';
  }

  /**
   * 生成响应策略
   */
  private generateResponseStrategy(
    intentResult: { intent: UserIntent; confidence: number },
    context: string,
    emotionalTone: 'positive' | 'neutral' | 'negative',
    userId?: string
  ): ResponseStrategy {
    const userProfile = userId ? this.getUserProfile(userId) : null;

    // 基于意图的基础策略
    let baseStrategy: ResponseStrategy;

    switch (intentResult.intent) {
      case UserIntent.QUESTION:
        baseStrategy = {
          tone: 'professional',
          length: 'moderate',
          structure: 'explanatory',
          includeExamples: true,
          includeFollowUp: true,
          priority: 'accuracy',
        };
        break;

      case UserIntent.INSTRUCTION:
        baseStrategy = {
          tone: 'professional',
          length: 'detailed',
          structure: 'step_by_step',
          includeExamples: true,
          includeFollowUp: false,
          priority: 'helpfulness',
        };
        break;

      case UserIntent.CONVERSATION:
        baseStrategy = {
          tone: 'casual',
          length: 'brief',
          structure: 'conversational',
          includeExamples: false,
          includeFollowUp: true,
          priority: 'engagement',
        };
        break;

      case UserIntent.COMPLAINT:
        baseStrategy = {
          tone: 'empathetic',
          length: 'moderate',
          structure: 'direct',
          includeExamples: false,
          includeFollowUp: true,
          priority: 'helpfulness',
        };
        break;

      case UserIntent.CREATIVE:
        baseStrategy = {
          tone: 'creative',
          length: 'detailed',
          structure: 'conversational',
          includeExamples: true,
          includeFollowUp: true,
          priority: 'engagement',
        };
        break;

      default:
        baseStrategy = {
          tone: 'professional',
          length: 'moderate',
          structure: 'direct',
          includeExamples: false,
          includeFollowUp: false,
          priority: 'helpfulness',
        };
    }

    // 根据情感倾向调整
    if (emotionalTone === 'negative') {
      baseStrategy.tone = 'empathetic';
      baseStrategy.includeFollowUp = true;
    } else if (emotionalTone === 'positive') {
      baseStrategy.tone =
        baseStrategy.tone === 'professional' ? 'professional' : 'casual';
    }

    // 根据用户画像调整
    if (userProfile) {
      if (userProfile.preferredTone) {
        baseStrategy.tone = userProfile.preferredTone as any;
      }
      if (userProfile.responseLength) {
        baseStrategy.length = userProfile.responseLength as any;
      }
    }

    return baseStrategy;
  }

  /**
   * 提取关键词
   */
  private extractKeywords(text: string): string[] {
    // 简单的关键词提取
    const words = text.match(/[\u4e00-\u9fa5a-zA-Z]{2,}/g) || [];
    const stopWords = [
      '什么',
      '如何',
      '怎么',
      '为什么',
      '可以',
      '能否',
      '请问',
      '这个',
      '那个',
      '我们',
      '你们',
    ];

    return words
      .filter(word => !stopWords.includes(word) && word.length > 1)
      .slice(0, 5);
  }

  /**
   * 获取用户画像
   */
  private getUserProfile(userId: string): UserProfile | null {
    return this.userProfiles.get(userId) || null;
  }

  /**
   * 更新用户画像
   */
  updateUserProfile(
    userId: string,
    intent: UserIntent,
    responseStrategy: ResponseStrategy,
    feedback?: 'positive' | 'negative'
  ): void {
    let profile = this.userProfiles.get(userId);

    if (!profile) {
      profile = {
        preferredTone: responseStrategy.tone,
        complexityLevel: 'medium',
        commonTopics: [],
        responseLength: responseStrategy.length,
        interactionStyle: responseStrategy.structure,
        totalInteractions: 0,
      };
    }

    profile.totalInteractions++;
    profile.lastInteractionTime = new Date();

    // 根据反馈调整偏好
    if (feedback === 'positive') {
      profile.preferredTone = responseStrategy.tone;
      profile.responseLength = responseStrategy.length;
    }

    this.userProfiles.set(userId, profile);
  }

  /**
   * 创建备用意图结果
   */
  private createFallbackIntentResult(message: string): IntentResult {
    return {
      intent: UserIntent.UNKNOWN,
      confidence: 0.1,
      keywords: this.extractKeywords(message),
      context: 'unknown',
      urgency: 'low',
      complexity: 'simple',
      emotionalTone: 'neutral',
      suggestedResponse: {
        tone: 'professional',
        length: 'moderate',
        structure: 'direct',
        includeExamples: false,
        includeFollowUp: true,
        priority: 'helpfulness',
      },
    };
  }

  /**
   * 格式化意图结果用于显示
   */
  formatIntentForDisplay(result: IntentResult): string {
    const intentNames = {
      [UserIntent.QUESTION]: '询问问题',
      [UserIntent.INSTRUCTION]: '指令请求',
      [UserIntent.CONVERSATION]: '日常对话',
      [UserIntent.CLARIFICATION]: '澄清说明',
      [UserIntent.COMPLAINT]: '投诉抱怨',
      [UserIntent.PRAISE]: '表扬赞美',
      [UserIntent.HELP]: '寻求帮助',
      [UserIntent.INFORMATION]: '信息查询',
      [UserIntent.CREATIVE]: '创意创作',
      [UserIntent.ANALYSIS]: '分析评估',
      [UserIntent.UNKNOWN]: '未知意图',
    };

    return (
      `🎯 **意图识别**: ${intentNames[result.intent]} (${(result.confidence * 100).toFixed(1)}%)\n` +
      `📊 **复杂度**: ${result.complexity} | **紧急度**: ${result.urgency}\n` +
      `😊 **情感**: ${result.emotionalTone}\n` +
      `🔑 **关键词**: ${result.keywords.join(', ')}`
    );
  }
}

// 导出单例实例
export const intentRecognitionService = new IntentRecognitionService();

// 导出类型
export type { IntentResult, ResponseStrategy, UserProfile };
